import tornado.web
import sae.const
import tornado.database
import os.path

from article import article
from comment import comment
from connection import Connection

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        Article = []
        
        db = Connection(sae.const.MYSQL_HOST+":"+sae.const.MYSQL_PORT,sae.const.MYSQL_DB, sae.const.MYSQL_USER, sae.const.MYSQL_PASS, 30)
        for article_ in db.query("SELECT * FROM article"):
            TempArticle = article()
            TempArticle.set(article_.id, article_.time, article_.content, article_.comments, article_.praise, article.step)
            Article.append(TempArticle)
        
        Article.sort(key = lambda article : article.Id, reverse = True)

        query = ""
        query = self.get_argument('query', '')
        
        if(query == ""):
            self.render("index.html", Article = Article)
        elif query == "hot":
            Article_hot = []
            Article.sort(key = lambda article : article.comments*20 + article.praise, reverse = True)
            for i in range(10):
                if i < len(Article):
                    Article_hot.append(Article[i])
            self.render("index.html", Article = Article_hot)
        elif query == "new":
            Article_new = []
            Article.sort(key = lambda article : article.Id, reverse = True)
            for i in range(10):
                if i < len(Article):
                    Article_new.append(Article[i])
            self.render("index.html", Article = Article_new)
        else:
            self.redirect("/comments?query="+query)

    def post(self):
        query_content = self.get_argument("query_content", "")
        db = Connection(sae.const.MYSQL_HOST+":"+sae.const.MYSQL_PORT,sae.const.MYSQL_DB, sae.const.MYSQL_USER, sae.const.MYSQL_PASS, 30)

        Article_query = []
        for article_ in db.query("SELECT * FROM article"):
            if article_.content.find(query_content) != -1:
                TempArticle = article()
                TempArticle.set(article_.id, article_.time, article_.content, article_.comments, article_.praise, article.step)
                Article_query.append(TempArticle)

        Article_query.sort(key = lambda article : article.Id, reverse = True)

        self.render("index.html", Article = Article_query)

        return
